const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const readSetting = require("../../lib/read_setting");
const CMD = require("../../lib/merge_video");

module.exports = (req, res) => {

    let { findPath, newname, outputPath, selectItems } = req.body;

    if (!newname.trim()) return res.send({ code: 400, msg: "未填写文件名称", result: '', ...req.body });

    outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');

    if (!findPath.trim()) return res.send({ code: 400, msg: "检索路径不存在", result: '', ...req.body });

    let typeArr = [];
    let meergeFiles = [];

    selectItems.forEach((item) => {
        typeArr.push(item.filename.split(".").pop());
        meergeFiles.push(path.resolve(findPath, item.filename));
    });

    typeArr = [...new Set(typeArr)];

    if (typeArr.length === 0) {
        return res.send({ code: 400, msg: "请选择要合并的文件", result: '', ...req.body });
    } else if (typeArr.length > 1) {
        return res.send({ code: 400, msg: "只能选择 “同类型” 文件！！！", result: '', ...req.body });
    }

    newname = `${newname}.${typeArr[0]}`;

    
    for (let i = 0; i < meergeFiles.length; i++) {
        if (!fs.existsSync(meergeFiles[i])) {
            return res.send({ code: 400, msg: `路径 ${filepath} 不存在！`, result: '', ...req.body });
        }
    }
    
    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }


    new Promise((resolve, reject) => {

        let savePath = path.resolve(outputPath, newname);

        if (fs.existsSync(savePath)) {
            return reject("目标目录下存在同名文件！！！")
        };

        let cmd = CMD(meergeFiles, savePath);
        // console.log(cmd);
        // return;
        exec(cmd, (err, stdout, stderr) => {
            if (err) return reject(err);
            resolve({ savePath, newname });
        })

    }).then(({ savePath, newname }) => {
        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })
        res.send({
            code: 200,
            state: true,
            filename: newname,
            result: savePath,
            msg: `${newname} 合并成功！`
        })
    }).catch(err => {
        console.log(err);
        let errObj = {
            code: 500,
            state: false,
            filename: newname,
            result: err,
            msg: `${newname} 合并失败！`
        };
        res.send(errObj);
    })
}